const express = require('express');
const path = require('path');
const app = require('express')();
const { createSocket } = require('dgram');
var fs =require('fs');
var options={
    key:fs.readFileSync('./cert/snakeoil.key'),
    cert:fs.readFileSync('./cert/snakeoil.pem')};


    const https = require('https').createServer(options,app);




app.get('/',(req,res)=>{
     res.send('<h1>Hello World Socket</h1>');
    //res.sendFile(__dirname+'/index.html');
 })

 //app.use('/js',app.static(__dirname+'/js'))

 app.use('/js', express.static(path.join(__dirname, 'js')));

 app.get('/tom',(req,res)=>{
     res.sendFile(__dirname+"/tom.html");
 })

 app.get('/jerry',(req,res)=>{
    res.sendFile(__dirname+"/jerry.html");
})

const io =require('socket.io')(https);

io.on('connection',(socket)=>{

console.log("new user connected"+socket.id);

socket.on('assignusername',(username)=>{
    socket.username=username;
    console.log("用户名"+socket.username+"   userid"+socket.id);
})

socket.on('joinRoom',(room)=>{
    socket.join(room);
    console.log(socket.username+"加入了 "+room+"房间")
})

socket.on('calljerry',(msg)=>{
    console.log("tom want jerry  "+msg);

    socket.to('room1').emit('beep',msg);
})


socket.on('signal',function(message){
    console.log('signal');
    console.dir(message);
    socket.to('room1').emit('signal',message);
});

socket.on('ice',function(message){
    console.log('ice  ');
    console.dir(message);
    socket.to('room1').emit('ice',message);
});


})


io.of("/").adapter.on("create-room",(room)=>{
    console.log(`room ${room} was created`);
})

io.of("/").adapter.on("join-room", (room, id) => {
    console.log(`socket ${id} has joined room ${room}`);
  });

  io.of("/").adapter.on("leave-room", (room, id) => {
    console.log(`socket ${id} has leave room ${room}`);
  });




 https.listen(443,'0.0.0.0');